let baseURL = "http://localhost:8000/api"

if (process.env.NODE_ENV === 'production') {
    baseURL = "";
}

const getToken = function() {
    return uni.getStorageSync("sea_token");
};

const setToken = function(val) {
    uni.setStorageSync("sea_token", val);
};

function getSystemInfo() {
    const app = getApp()
    const info = app.globalData?.systemInfo ?? {}
    info.version = app.globalData.version
    return info
}

function wrapParams(params) {
    const info = getSystemInfo()
    return {
        ...params,
        deviceId: info.deviceId ?? '',
        deviceBrand: info.deviceBrand ?? '',
        osName: info.osName ?? '',
        uniPlatform: info.uniPlatform ?? '',
        version: info.version ?? ''
    }
}
const http = {
    get: (path, params) => {
        params = wrapParams(params)
        let base_uri = path.startsWith("http") ? '' : baseURL
        return new Promise((resolve, reject) => {
            uni.request({
                url: base_uri + path + "?token=" + getToken(),
                method: "GET",
                data: params,
                success: (res) => {
                    resolve(res.data)
                },
                fail: (res) => {
                    reject(res);
                },
            });
        });
    },
    post: (path, params) => {
        params = wrapParams(params)
        let base_uri = path.startsWith("http") ? '' : baseURL
        return new Promise((resolve, reject) => {
            uni.request({
                url: base_uri + path + "?token=" + getToken(),
                method: "POST",
                data: params,
                success: (res) => {
                    resolve(res.data)
                },
                fail: (res) => {
                    reject(res);
                },
            });
        });
    }
}

export {
    getToken,
    setToken,
    http,
}